package vertx;

import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.Log4JLoggerFactory;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.handler.StaticHandler;
import io.vertx.ext.web.templ.thymeleaf.ThymeleafTemplateEngine;
import org.apache.log4j.Logger;
import org.slf4j.impl.Log4jLoggerFactory;

/**
 * @author 今何许
 * @date 2021-01-11 15:46
 */
public class StaticFileVerticle extends AbstractVerticle {
  ThymeleafTemplateEngine engine;
  Router router;

  @Override
  public void start(Promise<Void> startPromise) throws Exception {
    InternalLogger logger = Log4JLoggerFactory.getInstance(StaticFileVerticle.class);

    // Create a Router
    router = Router.router(vertx);

    engine = ThymeleafTemplateEngine.create(vertx);

    //配置静态文件路径
    router.route("/*").handler(StaticHandler.create());

    router.route("/").handler(req -> {
     logger.info("启动index...");
      JsonObject object = new JsonObject();
      object.put("name", "Hello Vertx thymeleaf");
      engine.render(object, "templates/index.html", bufferAsyncResult -> {
        if (bufferAsyncResult.succeeded()) {
          req.response()
            .putHeader("content-type", "text/html")
            .end(bufferAsyncResult.result());
        } else {
        }
      });

    });


    //绑定路由
    vertx.createHttpServer().requestHandler(router).listen(8888, http -> {
      if (http.succeeded()) {
        startPromise.complete();
        System.out.println("HTTP server started on port 8888");
      } else {
        startPromise.fail(http.cause());
      }
    });
  }
}
